import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Homework_TcpEchoServer {
    private ServerSocket socket = null;
    public Homework_TcpEchoServer(int port) throws IOException {
        //需要手动指定端口号
        socket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动！");
        ExecutorService service = Executors.newCachedThreadPool();
        while (true){
            //1.从操作系统中获取连接
            Socket clientSocket = socket.accept();
            //2.处理连接
            service.submit(new Runnable() {
                @Override
                public void run() {
                    processConnection(clientSocket);
                }
            });
        }
    }
    public void processConnection(Socket clientSocket){
        System.out.printf("[%s:%d] 客户端上线!\n", clientSocket.getInetAddress(), clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            //需要定义循环处理客户端请求
            while(true){
                if(!scanner.hasNext()){
                    System.out.printf("[%s:%d] 客户端下线！\n", clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }
                //1.等待接收客户请求
                String request = scanner.next();
                //2.根据请求，计算响应
                String response = process(request);
                //3.发送响应给客户端
                writer.println(response);
                writer.flush();
                //4.打印交互信息
                System.out.printf("[%s:%d] req=%s, resp=%s\n", clientSocket.getInetAddress(),
                        clientSocket.getPort(), request, response);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        Homework_TcpEchoServer server = new Homework_TcpEchoServer(9999);
        server.start();
    }
}
